import {Component, OnInit, ViewChild} from '@angular/core';
import {FormBuilder, FormGroup} from '@angular/forms';
import {NzMessageService} from 'ng-zorro-antd/message';
import {JobDescriptionService} from '../../service/job-description.service';
import {JobDescriptionQueryForm} from '../../types/req/JobDescriptionQueryForm';
import {SharedModule} from '../shared.module';
import {JobDescription} from '../../types/resp/JobDescription';
import {Page} from '../../types/page';
import {JobDescriptionAddComponent} from './job-description-add.component';
import {JobDescriptionViewComponent} from './job-description-view.component';
import {NzModalService} from 'ng-zorro-antd/modal';
import {EnterpriseSelectorComponent} from '../enterprise/enterprise-selector.component';
import {DepartmentSelectorComponent} from '../department/department-selector.component';
import { exportToExcel } from '../../utils/exportUtil'
import {getJobTypeText,getJobSalaryRangeText,getJobDescriptionStatusText} from "../../utils/dictTranslator";

@Component({
  selector: 'job-description-list',
  imports: [
    EnterpriseSelectorComponent,
    DepartmentSelectorComponent,
    JobDescriptionAddComponent,
    JobDescriptionViewComponent,
    SharedModule
  ],
  templateUrl: './job-description-list.component.html',
  standalone: true
})
export class JobDescriptionListComponent implements OnInit {
  searchForm!: FormGroup;
  searchLoading: boolean = false
  listOfData: JobDescription[] = [];
  total: number = 0

  @ViewChild(EnterpriseSelectorComponent, { static: false }) enterpriseSelectorComponent!: EnterpriseSelectorComponent;
  @ViewChild(DepartmentSelectorComponent, { static: false }) departmentSelectorComponent!: DepartmentSelectorComponent;
  @ViewChild(JobDescriptionAddComponent, { static: false }) jobDescriptionAddComponent!: JobDescriptionAddComponent;
  @ViewChild(JobDescriptionViewComponent, { static: false }) jobDescriptionViewComponent!: JobDescriptionViewComponent;

  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    private jobDescriptionService: JobDescriptionService,
    private modal: NzModalService
  ) {}

  ngOnInit(): void {
    this.searchForm = this.fb.group({
      enterpriseId: [0],
      enterpriseName: [''],
      jobTitle: [''],
      departmentId: [0],
      departmentName: [''],
    })
    this.onSearch()
  }

  onReset() {
    this.searchForm.reset()
  }

  onSearch() {
    try {
      this.searchLoading = true
      this.jobDescriptionService.find(new JobDescriptionQueryForm(this.searchForm.value)).subscribe({
        next: (resp) => {
          if (!resp || resp.code !== 1) {
            this.message.error(resp && resp.msg ? resp.msg : '操作异常')
            return
          }
          const page: Page<JobDescription> | undefined = resp.data
          if (page && page.list.length > 0) {
            this.listOfData = page.list
            this.total = page.total
          }
        },
        complete: () => {
          this.searchLoading = false
        }
      })
    } catch (e) {
      console.log('获取数据异常', e)
    }
  }

  onAdd() {
    this.jobDescriptionAddComponent.display(0)
  }

  onExport() {
    try {
      const headers = ['企业名称','岗位名称','部门名称','工作地点','岗位类型','岗位职责','岗位要求','薪资范围','发布日期','截止日期','招聘人数','状态']
      this.searchLoading = true
      this.jobDescriptionService.find(new JobDescriptionQueryForm(this.searchForm.value)).subscribe({
        next: (resp) => {
          if (!resp || resp.code !== 1 || !resp.data || resp.data.list.length < 1) {
            this.message.error('无数据导出')
            return
          }
          const exportData = []
          for (const d of resp.data.list) {
            exportData.push([d.enterpriseName,d.jobTitle,d.departmentName,d.workLocation,getJobTypeText(d.jobType),d.responsibilities,d.requirement,getJobSalaryRangeText(d.salaryRange),d.postingDate,d.closingDate,d.headCount,getJobDescriptionStatusText(d.status)])
          }
          exportToExcel(headers, exportData)
        },
        complete: () => {
          this.searchLoading = false
        }
      })
    } catch (e) {
      console.log('获取数据异常', e)
    }
  }

  editRow(id: number) {
    this.jobDescriptionAddComponent.display(id)
  }

  delRow(id: number) {
    this.modal.confirm({
      nzTitle: '<i>删除提示</i>',
      nzContent: '<b>确定要删除吗?</b>',
      nzOnOk: () => {
        this.jobDescriptionService.del(id).subscribe({
          next: (resp) => {
            if (resp && resp.code === 1) {
              this.message.success('删除成功!')
              this.onSearch()
            } else {
              this.message.error('操作失败:' + (resp.msg ? resp.msg : '原因未知'))
            }
          },
          complete: () => {
            this.searchLoading = false
          }
        })
      }
    });
  }

  detailRow(record: JobDescription) {
    this.jobDescriptionViewComponent.display(record)
  }

  findEnterprise() {
    this.enterpriseSelectorComponent.display()
  }

  handleEnterpriseSelectedEvent(selectedEnterprise: { enterpriseId?: number; enterpriseName?: string; }) {
    if (selectedEnterprise && 'enterpriseId' in selectedEnterprise) {
      this.searchForm.patchValue(selectedEnterprise);
    }
  }

  findDepartment() {
    this.departmentSelectorComponent.display()
  }

  handleDepartmentSelectedEvent(selectedDepartment: { departmentId?: number; departmentName?: string; }) {
    if (selectedDepartment && 'departmentId' in selectedDepartment) {
      this.searchForm.patchValue(selectedDepartment);
    }
  }

  onAdded(addedFlag: boolean) {
    if (addedFlag) {
      this.onSearch()
    }
  }
}
